<template>
  <div class="content-view">

    <pageHead>
      <div>
        <Button shape="circle" :loading="loadBtn" type="success" icon="md-git-network" @click="regenerate">重新生成</Button>
        <Button class="ml5" type="primary" @click="showAddWarp">新增</Button>
      </div>
    </pageHead>
    <div class="table-body">
      <Tables ref="tables" :columns="gridOption.columns" :value="gridOption.data">
      </Tables>
    </div>

    <editModal ref="editModal" width="60" :columns="gridOption.editColumns" :rules='gridOption.rules'>
      <div slot="bottom">

        <fieldItem name='前端控件类型' style="width:90%;" :required="true">
          <frontEndControlType v-model="editRow.control" ref="frontEndControlType" @changeOption="changeOption"></frontEndControlType>
        </fieldItem>

        <fieldItem name='数据库类型' style="width:90%;" :required="true">
          <databaseType v-model="editRow.data_type" ref="databaseType"></databaseType>
        </fieldItem>

        <fieldItem name='数据库长度' style="width:90%;" :required="true">
          <InputNumber v-model="editRow.data_length" style="width:100%;"></InputNumber>
        </fieldItem>
      </div>
    </editModal>

  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import modelFieldServer from '@/api/system_high/modelFieldServer'
import modelServer from '@/api/system_high/modelServer'
import uiTool from '@/libs/uiTool'

import databaseType from './com/databaseType'
import frontEndControlType from './com/frontEndControlType'

export default {
  name: 'tables_page',
  components: {
    databaseType,
    frontEndControlType,
  },

  data() {
    let $this = this
    let editColumns = [
      { title: '字段key', key: 'key', placeholder: '例: user_id' },
      { title: '字段名称', key: 'name', placeholder: '例: 用户名称' },
      {
        title: '数据模型id',
        key: 'model_id',
        disabled: true,
        com: 'Select',
        source: [],
        render(h, param) {
          let row = param.column.source.find((p) => parseInt(p.key) === parseInt(param.row.model_id))
          if (row) {
            return <span>{row.value}</span>
          }
        },
      },
      {
        title: '是否为空',
        key: 'allow_null',
        com: 'Radio',
        source: [
          { key: 0, value: '否' },
          { key: 1, value: '是' },
        ],
        render(h, params) {
          let str = params.row.allow_null ? '是' : '否'
          return <span>{str}</span>
        },
      },
      {
        title: '排序',
        key: 'sort',
        com: 'InputNumber',
        render(h, params) {
          let row = params.row
          return h('div', { class: 'sort-num' }, [
            h('Icon', {
              props: { type: 'md-arrow-up' },
              on: {
                click: () => {
                  $this.sortUp(row)
                },
              },
            }),
            h('Icon', {
              props: { type: 'md-arrow-down' },
              on: {
                click: () => {
                  $this.sortDown(row)
                },
              },
            }),
          ])
        },
      },
      { title: '默认值', key: 'default_value' },
    ]
    return {
      model_id: '',
      loadBtn: false,
      editRow: {
        allow_null: 0,
      },
      gridOption: {
        rules: {
          key: [{ required: true, message: '请填写字段key' }],
          name: [{ required: true, message: '请填写昵称' }],
          model_id: [{ required: true, message: '请选择model' }],
          allow_null: [{ required: true, message: '请填写昵称' }],
          sort: [{ required: true, message: '请填写昵称' }],
        },
        editColumns,
        columns: [
          { title: 'id', key: 'id', width: '80px', is_show_edit: 0 },
          ...editColumns,
          {
            title: '字段是否已同步',

            key: 'isDbExist',
            render(h, params) {
              let isDbExist = params.row.isDbExist
              if (isDbExist) {
                return <span class="buld bold">是</span>
              } else {
                return <span class="red bold">否</span>
              }
            },
          },
          {
            title: '前端控件',
            key: 'control',
            render(h, params) {
              let control = typeof params.row.control === 'string' ? JSON.parse(params.row.control) : params.row.control
              return (
                <div>
                  <div> 类型：{control.comType}</div>
                </div>
              )
            },
          },
          {
            title: '数据库类型',
            key: 'data_type',
          },

          {
            title: '操作',
            key: 'action',
            type: 'template',
            render: (h, params) => {
              let btns = [
                {
                  title: '修改',
                  type: 'primary',
                  click: () => {
                    this.showEditModal(params.row)
                  },
                },
                {
                  title: '删除',
                  type: 'primary',
                  click: () => {
                    this.delConfirm(params.row)
                  },
                },
              ]

              return uiTool.getBtn(h, btns)
            },
          },
        ],
        data: [],
      },
    }
  },
  computed: {
    ...mapGetters({
      shopList: 'shop/shopList',
    }),
    disabledBtn() {
      if (this.gridOption.data && this.gridOption.data.length > 0) {
        return false
      } else {
        return true
      }
    },
  },
  created() {
    let params = this.$route.params
    if (params && params.id) {
      this.model_id = parseInt(params.id)
    }
    this.initCol()
    this.init()
  },
  watch: {},
  methods: {
    async init() {
      let model_id = this.model_id
      let res = await modelFieldServer.all({ model_id })
      this.gridOption.data = res.data
    },

    async initCol() {
      let res = await modelServer.all()

      let row = this.gridOption.columns.find((p) => p.key === 'model_id')
      if (row) {
        row.source = res.data.map((p) => {
          let { id, name, key } = p
          return { key: id, value: key + '_' + name }
        })
      }
    },
    changeOption(option) {
      Object.keys(option).forEach((key) => {
        this.editRow[key] = option[key]
      })
    },

    showAddWarp() {
      let model_id = this.model_id

      let sort = this.gridOption.data.length + 1
      this.editRow = {
        data_length: 100,
        allow_null: 0,
        sort,
        default_value: '',
        model_id,
        control: {},
      }

      this.$refs.editModal.addShow(this.editRow, async (row) => {
        let control = typeof row.control === 'string' ? this.editRow.control : JSON.stringify(row.control)
        await modelFieldServer.add(Object.assign(row, { model_id, control }))

        rootVue.$Message.success('新增成功！')
        this.init()
      })
    },
    showEditModal(row) {
      let model_id = this.model_id
      this.editRow = row
      if (row.control) {
        this.editRow.control = typeof row.control === 'string' ? JSON.parse(row.control) : row.control
      } else {
        row.control = { comType: 'Input' }
      }

      this.$refs.editModal.editShow(this.editRow, async (newRow) => {
        let control = JSON.stringify(this.editRow.control)
        let data_type = this.editRow.data_type

        await modelFieldServer.edit(Object.assign({}, newRow, { model_id, control, data_type }))
        rootVue.$Message.success('修改成功！')

        this.init()
      })
    },
    async delConfirm(row) {
      uiTool.delConfirm(async () => {
        await modelFieldServer.del(row)
        rootVue.$Message.success('删除成功！')
        this.init()
      })
    },
    async regenerate() {
      let id = this.model_id
      uiTool.showConfirm({ content: '你确定生成吗，生成将覆盖原来已存在model和controller,请谨慎操作' }, async () => {
        this.loadBtn = true
        await modelServer.regenerate({ id })
        this.loadBtn = false
        rootVue.$Message.success('生成成功！')
        this.init()
      })
    },
    async sortUp(row) {
      let { id, sort } = row
      if (sort >= 1) {
        await modelFieldServer.edit({ id, sort: sort - 1 })
        this.init()
      } else {
        this.$Message.error('排序不能在小')
      }
    },
    async sortDown(row) {
      let { id, sort } = row
      await modelFieldServer.edit({ id, sort: sort + 1 })
      this.init()
    },
  },
}
</script>
